<template>
  <div class="log-view">
    <a-card class="log-card">
      <!-- 搜索表单 -->
      <a-form :model="searchForm" layout="horizontal">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item field="operateUser" label="操作用户">
              <a-input
                v-model="searchForm.operateUser"
                placeholder="请输入操作用户"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="operateType" label="操作类型">
              <a-select
                v-model="searchForm.operateType"
                placeholder="请选择操作类型"
                allow-clear
              >
                <a-option value="login">登录操作</a-option>
                <a-option value="logout">登出操作</a-option>
                <a-option value="insert">新增操作</a-option>
                <a-option value="update">更新操作</a-option>
                <a-option value="delete">删除操作</a-option>
                <a-option value="query">查询操作</a-option>
                <a-option value="system">系统操作</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="status" label="操作状态">
              <a-select
                v-model="searchForm.status"
                placeholder="请选择操作状态"
                allow-clear
              >
                <a-option value="success">成功</a-option>
                <a-option value="fail">失败</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="timeRange" label="操作时间">
              <a-range-picker
                v-model="searchForm.timeRange"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24" style="text-align: right">
            <a-space>
              <a-button type="primary" @click="loadData">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="resetSearch">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
              <a-button type="outline" status="danger" @click="handleClearLog">
                <template #icon>
                  <icon-delete />
                </template>
                清空日志
              </a-button>
              <a-button type="outline" @click="handleExportLog">
                <template #icon>
                  <icon-download />
                </template>
                导出日志
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 日志表格 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data="logList"
        :pagination="pagination"
        :loading="loading"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 操作类型 -->
        <template #operateType="{ record }">
          <a-tag :color="getOperateTypeColor(record.operateType)">{{
            getOperateTypeText(record.operateType)
          }}</a-tag>
        </template>

        <!-- 操作状态 -->
        <template #status="{ record }">
          <a-tag :color="record.status === 'success' ? 'green' : 'red'">
            {{ record.status === "success" ? "成功" : "失败" }}
          </a-tag>
        </template>

        <!-- 消耗时间 -->
        <template #consumeTime="{ record }">
          {{ record.consumeTime }} ms
        </template>

        <!-- 操作列 -->
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="viewLogDetail(record)">
              详情
            </a-button>
            <a-popconfirm
              content="确定要删除该日志记录吗？"
              @ok="deleteLog(record.id)"
            >
              <a-button type="text" size="small" status="danger">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 日志详情抽屉 -->
    <a-drawer v-model:visible="drawerVisible" :width="600" title="日志详情">
      <a-descriptions :data="logDetailData" layout="vertical" bordered />
      <template v-if="currentLog.requestParam || currentLog.responseData">
        <a-divider />
        <a-typography-title :heading="6">请求参数</a-typography-title>
        <a-textarea
          v-model="formattedRequestParam"
          readonly
          :auto-size="{ minRows: 5, maxRows: 15 }"
        />

        <a-divider />
        <a-typography-title :heading="6">响应数据</a-typography-title>
        <a-textarea
          v-model="formattedResponseData"
          readonly
          :auto-size="{ minRows: 5, maxRows: 15 }"
        />
      </template>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { Message, Modal } from "@arco-design/web-vue";

// 表格列定义
const columns = [
  { title: "ID", dataIndex: "id", width: 80 },
  { title: "操作模块", dataIndex: "module" },
  {
    title: "操作类型",
    dataIndex: "operateType",
    slotName: "operateType",
    width: 100,
  },
  { title: "操作描述", dataIndex: "description" },
  { title: "操作人员", dataIndex: "operateUser" },
  { title: "IP地址", dataIndex: "ipAddress", width: 130 },
  { title: "操作状态", dataIndex: "status", slotName: "status", width: 80 },
  {
    title: "消耗时间",
    dataIndex: "consumeTime",
    slotName: "consumeTime",
    width: 100,
  },
  { title: "操作时间", dataIndex: "createTime", width: 180 },
  {
    title: "操作",
    dataIndex: "operations",
    slotName: "operations",
    width: 120,
    fixed: "right",
  },
];

// 搜索表单数据
const searchForm = reactive({
  operateUser: "",
  operateType: "",
  status: "",
  timeRange: [],
  current: 1,
  pageSize: 10,
});

// 日志列表数据
const logList = ref([
  {
    id: 1,
    module: "用户管理",
    operateType: "login",
    description: "用户登录",
    operateUser: "admin",
    ipAddress: "192.168.1.1",
    status: "success",
    consumeTime: 56,
    createTime: "2023-08-15 10:23:45",
    requestParam: '{"userAccount":"admin","userPassword":"******"}',
    responseData:
      '{"code":0,"data":{"id":1,"userAccount":"admin","userName":"管理员"},"message":"success"}',
  },
  {
    id: 2,
    module: "题目管理",
    operateType: "insert",
    description: "创建题目",
    operateUser: "admin",
    ipAddress: "192.168.1.1",
    status: "success",
    consumeTime: 128,
    createTime: "2023-08-15 11:35:21",
    requestParam:
      '{"title":"两数之和","content":"给定一个整数数组...","tags":["数组","哈希表"]}',
    responseData: '{"code":0,"data":1,"message":"success"}',
  },
  {
    id: 3,
    module: "用户管理",
    operateType: "update",
    description: "修改用户信息",
    operateUser: "admin",
    ipAddress: "192.168.1.1",
    status: "success",
    consumeTime: 87,
    createTime: "2023-08-15 14:12:36",
    requestParam: '{"id":2,"userName":"张三","userRole":"user"}',
    responseData: '{"code":0,"data":true,"message":"success"}',
  },
  {
    id: 4,
    module: "题目管理",
    operateType: "delete",
    description: "删除题目",
    operateUser: "admin",
    ipAddress: "192.168.1.1",
    status: "fail",
    consumeTime: 32,
    createTime: "2023-08-15 15:45:18",
    requestParam: '{"id":5}',
    responseData: '{"code":500,"message":"操作失败：该题目有关联的提交记录"}',
  },
  {
    id: 5,
    module: "系统管理",
    operateType: "system",
    description: "修改系统配置",
    operateUser: "admin",
    ipAddress: "192.168.1.1",
    status: "success",
    consumeTime: 65,
    createTime: "2023-08-15 16:23:09",
    requestParam:
      '{"systemName":"黄海OJ在线判题系统","adminEmail":"admin@example.com"}',
    responseData: '{"code":0,"data":true,"message":"success"}',
  },
]);

const total = ref(5);
const loading = ref(false);
const drawerVisible = ref(false);
const currentLog = ref({} as any);

// 分页配置
const pagination = reactive({
  total: 5,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 格式化请求参数
const formattedRequestParam = computed(() => {
  if (!currentLog.value.requestParam) {
    return "";
  }
  try {
    const parsed = JSON.parse(currentLog.value.requestParam);
    return JSON.stringify(parsed, null, 2);
  } catch (e) {
    return currentLog.value.requestParam;
  }
});

// 格式化响应数据
const formattedResponseData = computed(() => {
  if (!currentLog.value.responseData) {
    return "";
  }
  try {
    const parsed = JSON.parse(currentLog.value.responseData);
    return JSON.stringify(parsed, null, 2);
  } catch (e) {
    return currentLog.value.responseData;
  }
});

// 日志详情描述项
const logDetailData = computed(() => {
  return [
    {
      label: "日志编号",
      value: currentLog.value.id,
    },
    {
      label: "操作模块",
      value: currentLog.value.module,
    },
    {
      label: "操作类型",
      value: getOperateTypeText(currentLog.value.operateType),
    },
    {
      label: "操作描述",
      value: currentLog.value.description,
    },
    {
      label: "操作人员",
      value: currentLog.value.operateUser,
    },
    {
      label: "IP地址",
      value: currentLog.value.ipAddress,
    },
    {
      label: "操作状态",
      value: currentLog.value.status === "success" ? "成功" : "失败",
    },
    {
      label: "消耗时间",
      value: `${currentLog.value.consumeTime} ms`,
    },
    {
      label: "操作时间",
      value: currentLog.value.createTime,
    },
  ];
});

// 获取操作类型文本
const getOperateTypeText = (type: string) => {
  switch (type) {
    case "login":
      return "登录操作";
    case "logout":
      return "登出操作";
    case "insert":
      return "新增操作";
    case "update":
      return "更新操作";
    case "delete":
      return "删除操作";
    case "query":
      return "查询操作";
    case "system":
      return "系统操作";
    default:
      return "未知";
  }
};

// 获取操作类型颜色
const getOperateTypeColor = (type: string) => {
  switch (type) {
    case "login":
    case "logout":
      return "blue";
    case "insert":
      return "green";
    case "update":
      return "orange";
    case "delete":
      return "red";
    case "query":
      return "purple";
    case "system":
      return "cyan";
    default:
      return "gray";
  }
};

// 加载日志数据
const loadData = async () => {
  loading.value = true;
  // 这里应该调用后端API查询日志数据
  // 模拟API调用延迟
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.operateUser = "";
  searchForm.operateType = "";
  searchForm.status = "";
  searchForm.timeRange = [];
  pagination.current = 1;
  loadData();
};

// 分页变化
const onPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

// 每页条数变化
const onPageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  loadData();
};

// 查看日志详情
const viewLogDetail = (record: any) => {
  currentLog.value = record;
  drawerVisible.value = true;
};

// 删除日志
const deleteLog = async (id: number) => {
  // 这里应该调用后端API删除日志
  Message.success(`日志记录 ${id} 删除成功`);
  loadData();
};

// 清空日志
const handleClearLog = () => {
  Modal.warning({
    title: "清空日志",
    content: "确定要清空所有日志记录吗？此操作将无法恢复！",
    okButtonProps: { status: "danger" },
    onOk: () => {
      // 这里应该调用后端API清空日志
      Message.success("日志清空成功");
      loadData();
    },
  });
};

// 导出日志
const handleExportLog = () => {
  // 这里应该调用后端API导出日志
  Message.success("日志导出成功");
};

// 组件挂载后加载数据
loadData();
</script>

<style scoped>
.log-view {
  padding: 0;
}

.log-card,
.table-card {
  margin-bottom: 16px;
}
</style>
